var fs = require('fs');
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
var  multiparty = require( "connect-multiparty" );
const interimMultiparty = multiparty()

app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json({limit: '50mb'}))

// const rootAssetUrl = 'F:/Zyun/Project/competence-scratch/static/internalapi/asset'
// const rootJSONUrl = 'F:/Zyun/Project/competence-scratch/static/json_index'
// const rootAssetUrl = '/www/wwwroot/cc.cc.com/source/static/internalapi/asset'
// const rootJSONUrl = '/www/wwwroot/cc.cc.com/source/static/json_index'
const rootAssetUrl = '/opt/competence-edu/nginx/web/scratch/static/internalapi/asset'
const rootJSONUrl = '/opt/competence-edu/nginx/web/scratch/static/json_index'
const feedbackMsg = {
    data:'',
    success: true,
    msg:'操作成功'
}
const feedbackMsgErr = {
    data:'',
    success: true,
    msg:'操作失败'
}

// 改尺寸
app.post('/mark/editSprite', interimMultiparty, function(req,res){
    const {data, base64} = req.body;
    const assets = JSON.parse(data);
    const {name, assetId, dataFormat } = assets;
    const Url = `${rootAssetUrl}/${assetId}.${dataFormat}`
    const updateBase64 = base64.replace(/\s/g, '+').replace(/^data:image\/\w+;base64,/,'')
    const imageBuffer = new Buffer.from(updateBase64, "base64");
    fs.writeFile(Url, imageBuffer, (err) => {
        if (err) return res.send(feedbackMsgErr)
        res.send(feedbackMsg)
    });
})

app.post('/mark/editSpriteSvg', function(req,res){
    const wbody = req.body;
    const {name, image, assetId, dataFormat } = wbody;
    // 删除旧的
    const Url = `${rootAssetUrl}/${assetId}.${dataFormat}`
    const wstream = fs.createWriteStream(Url);
    if (dataFormat === 'svg') {
        fs.writeFile(`${Url}`, image, (err) => {
            if (err) return res.send({...feedbackMsgErr,data:parseJSON})
            res.send(feedbackMsg)
        })
    } else {
        wstream.on('open', () => {
            const { data } = image;
            let arr = []
            for(let key in data) {
                arr.push(data[key])
            }
            const earray1 = new Uint8Array(arr)
            wstream.write(earray1);
            wstream.end(() => {
                console.log('sound end')
            })
        })
        wstream.on('error', (err) => { console.log('stream error', err) });
        wstream.on('finish', () => {
            res.send(feedbackMsg)
        });
    }
})

// 删背景
app.get('/mark/bgData',function(req,res){
    fs.readFile(`${rootJSONUrl}/backdrops.json`, 'utf8', function(err, result){
        if (err) return res.send(feedbackMsgErr)
        res.send({...feedbackMsg, data:JSON.parse(result)})
    });
})
app.post('/mark/deleteBg',function(req,res){
    const wbody = req.body;
    const { assetIdList } = wbody
    // 删sprite.json
    fs.readFile(`${rootJSONUrl}/backdrops.json`, 'utf8', function(err, result){
        if (err) {
            return error({...err, ...feedbackMsgErr});
         }
        const parseJSON = JSON.parse(result)
        const remainBg= parseJSON.filter((item) => {
            return !assetIdList.includes(item.assetId)
        })
        const strJSON = JSON.stringify(remainBg)
        const buffer = new Buffer(strJSON)
        fs.writeFile(`${rootJSONUrl}/backdrops.json`, buffer, (err) => {
            if (err) return res.send({...feedbackMsgErr,data:parseJSON})
            res.send({...feedbackMsg, data:remainBg})
        })
    });
})
// 删背景--end

// 删角色
app.get('/mark/data',function(req,res){
    fs.readFile(`${rootJSONUrl}/sprites.json`, 'utf8', function(err, result){
        if (err) res.send(feedbackMsgErr)
        res.send({...feedbackMsg, data:JSON.parse(result)})
    });
})

app.post('/mark/deleteSprite',function(req,res){
    const wbody = req.body;
    const { spriteNames, soundAssetIds, costumeAssetIds, soundNames, costumeNames } = wbody
    // 删sprite.json
    const spritePromise = new Promise((resolve, error) => {
        fs.readFile(`${rootJSONUrl}/sprites.json`, 'utf8', function(err, result){
            if (err) {
                return error({...err, ...feedbackMsgErr});
             }
            const parseJSON = JSON.parse(result)
            const remainSprite = parseJSON.filter((item) => {
                return !spriteNames.includes(item.name)
            })
            const strJSON = JSON.stringify(remainSprite)
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/sprites.json`, buffer, (err) => {
                if (err) return error(feedbackMsgErr)
                resolve(feedbackMsg)
            })
        });
    })
    
    // 删costume.json
    const costumePromise = new Promise((resolve, error) => {
        fs.readFile(`${rootJSONUrl}/costumes.json`, 'utf8', function(err, result){
            if (err) {
                return error({...err, ...feedbackMsgErr});
             }
            const parseJSON = JSON.parse(result)
            // 删 素材
            const delCostume = parseJSON.filter((item) => {
                return costumeNames.includes(item.name)
            })
            delCostume.forEach((item) => {
                const delUrl = rootAssetUrl + '/' + item.md5ext
                fs.unlink(delUrl, (rsp) => {
                    console.log(rsp)
                })
            })
            // 删 素材--end
    
            // 刷新目录
            const remainCostume = parseJSON.filter((item) => {
                return !costumeNames.includes(item.name)
            })
            const strJSON = JSON.stringify(remainCostume)
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/costumes.json`, buffer, (err) => {
                if (err) return error({...err, ...feedbackMsgErr});
                resolve(feedbackMsg)
            })
            // 刷新目录--end
        });
    })
    
    // 删sound.json
    const soundPromise = new Promise((resolve, error) => {
        fs.readFile(`${rootJSONUrl}/sounds.json`, 'utf8', function(err, result){
            if (err) {
                return error({...err, ...feedbackMsgErr});
             }
            const parseJSON = JSON.parse(result)
            // 删 素材
            const delSounds = parseJSON.filter((item) => {
                return soundNames.includes(item.name)
            })
            delSounds.forEach((item) => {
                const delUrl = rootAssetUrl + '/' + item.md5ext
                fs.unlink(delUrl, (rsp) => {
                    console.log(rsp)
                })
            })
            // 删 素材--end
    
            // 刷新目录
            const remainSound = parseJSON.filter((item) => {
                return !soundNames.includes(item.name)
            })
            const strJSON = JSON.stringify(remainSound)
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/sounds.json`, buffer, (err) => {
                if (err) return error({...err, ...feedbackMsgErr});
                resolve(feedbackMsg)
            })
            // 刷新目录--end
        });
    })

    //spritePromise
    //costumePromise
    //soundPromise
    spritePromise.then((rsp) => {
        const { success, msg } = rsp
        if (!success) return alert(msg)
        return costumePromise
    }).then((rsp) => {
        const { success, msg } = rsp
        if (!success) return alert(msg)
        return soundPromise
    }).then((rsp) => {
        const { success, msg } = rsp
        if (!success) return alert(msg)
        res.send(feedbackMsg)
    })
})
// 删角色--end

app.post('/mark/rawbackground', function(req,res){
    const wbody = req.body;
    const { assetId, dataFormat, name, asset } = wbody;
    const { data } = asset;
    const spriteFile = `${assetId}.${dataFormat}`
    const filePath = `${rootAssetUrl}/${spriteFile}`;
    const wstream = fs.createWriteStream(filePath);
    const background = {
        name,
        tags:['custom'],
        assetId,
        bitmapResolution:2,
        dataFormat,
        md5ext:spriteFile,
        rotationCenterX:480,
        rotationCenterY:360
    }
    wstream.on('open', () => {
        let arr = []
        for(let key in data) {
            arr.push(data[key])
        }
        const earray = new Uint8Array(arr)
        wstream.write(earray);
        wstream.end(() => {
            console.log('sound end')
        })
    })
    wstream.on('error', (err) => { console.log('stream error', err) });
    wstream.on('finish', () => {
        fs.readFile(`${rootJSONUrl}/backdrops.json`, 'utf8', function(err, result){
            if (err) {
                return console.log('文件读取失败!' + err.message);
             }
            const parseJSON = JSON.parse(result)
            const strJSON = JSON.stringify([...parseJSON, background])
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/backdrops.json`, buffer, (err) => {
                if (err) return res.send(feedbackMsgErr);
                res.send(feedbackMsg);
            })
        });

    });
    
})

app.post('/mark/sound',function(req,res){
    const wbody = req.body;
    const { assetId, dataFormat, name, asset, spriteName } = wbody;
    const { data } = asset;
    const spriteFile = `${assetId}.${dataFormat}`
    const filePath = `${rootAssetUrl}/${spriteFile}`;
    let spriteData = {}
    const promise = new Promise((resove, error) => {
        fs.readFile(`${rootJSONUrl}/sprites.json`, 'utf8', function(err, result){
            if (err) {
                return console.log('文件读取失败!' + err.message);
             }
             spriteData = JSON.parse(result)
             let isCustome = false
             spriteData.forEach((item, index) => {
                if ([spriteName].includes(item.name)) {
                    isCustome = item.tags.includes('custom')
                }
            })
            resove(isCustome)
        })
    })

    promise.then((rsp) => {
        if (!rsp) return
        const wstream = fs.createWriteStream(filePath);
        wstream.on('open', () => {
            let arr = []
            for(let key in data) {
                arr.push(data[key])
            }
            const earray = new Uint8Array(arr)
            wstream.write(earray);
            wstream.end(() => {
                console.log('sound end')
            })
        })
        wstream.on('error', (err) => { console.log('stream error') });
        wstream.on('finish', () => {
            const sound = {
                name,
                tags:['custom'],
                assetId,
                dataFormat,
                format:'',
                md5ext:spriteFile,
                sampleCount:9145,
                rate:22050
            };
            spriteData.forEach((item, index) => {
                if ([spriteName, 'Cat'].includes(item.name)) {
                    spriteData[index].sounds = [...spriteData[index].sounds, sound]
                }
            })
            const strJSON = JSON.stringify(spriteData)
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/sprites.json`, buffer, (err) => {
                if (err) return res.send(feedbackMsgErr)
            })
            fs.readFile(`${rootJSONUrl}/sounds.json`, 'utf8', function(err, result){
                if (err) {
                    return res.send(feedbackMsgErr)
                 }
                const parseJSON = JSON.parse(result)
                // 遍历找出spriteName所在的位置
                const strJSON = JSON.stringify([...parseJSON, sound])
                const buffer = new Buffer(strJSON)
                fs.writeFile(`${rootJSONUrl}/sounds.json`, buffer, (err) => {
                    if (err) return res.send(feedbackMsgErr)
                    res.send(feedbackMsg)
                })
            });
        });
    })
})

app.post('/mark/costume',function(req,res){
    const wbody = req.body;
    const { assetId, dataFormat, name, asset, spriteName } = wbody;
    const { data } = asset;
    const spriteFile = `${assetId}.${dataFormat}`
    const filePath = `${rootAssetUrl}/${spriteFile}`;
    let spriteData = {}
    // 判断是否是自定义角色, 保持原生的角色不变
    const promise = new Promise((resove, error) => {
        fs.readFile(`${rootJSONUrl}/sprites.json`, 'utf8', function(err, result){
            if (err) {
                return console.log('文件读取失败!' + err.message);
             }
             spriteData = JSON.parse(result)
             let isCustome = false
             spriteData.forEach((item, index) => {
                if ([spriteName].includes(item.name)) {
                    isCustome = item.tags.includes('custom')
                }
            })
            resove(isCustome)
        })
    })

    promise.then((rsp) => {
        if (!rsp) return
        const wstream = fs.createWriteStream(filePath);
        wstream.on('open', () => {
            let arr = []
            for(let key in data) {
                arr.push(data[key])
            }
            const earray = new Uint8Array(arr)
            wstream.write(earray);
            wstream.end(() => {
                console.log('costume end')
            })
        })
        wstream.on('error', (err) => { console.log('stream error') });
        wstream.on('finish', () => {
            const costume = {
                name,
                assetId,
                bitmapResolution:2,
                dataFormat,
                md5ext:spriteFile,
                rotationCenterX:30,
                rotationCenterY:30
            };
            spriteData.forEach((item, index) => {
                if ([spriteName, 'Cat'].includes(item.name)) {
                    spriteData[index].costumes = [...spriteData[index].costumes, costume]
                }
            })
            const strJSON = JSON.stringify(spriteData)
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/sprites.json`, buffer, (err) => {
                if (err) return res.send(feedbackMsgErr);
            })
            fs.readFile(`${rootJSONUrl}/costumes.json`, 'utf8', function(err, result){
                if (err) {
                    return res.send(feedbackMsgErr);
                 }
                const parseJSON = JSON.parse(result)
                // 遍历找出spriteName所在的位置
                const strJSON = JSON.stringify([...parseJSON, {...costume, tags:['custom']}])
                const buffer = new Buffer(strJSON)
                fs.writeFile(`${rootJSONUrl}/costumes.json`, buffer, (err) => {
                    if (err) return res.send(feedbackMsgErr);
                    res.send(feedbackMsg)
                })
            });
        });
    })
    
})

app.post('/mark/sprite', function(req,res){
    const wbody = req.body;
    const { costumes } = wbody;
    const sprite = costumes[0]
    const { assetId, dataFormat, name, asset } = sprite;
    const capitalizedName = name[0].toUpperCase()+name.substr(1)
    const lowerCaseName = name[0].toLowerCase()+name.substr(1)
    const { data } = asset;
    const spriteFile = `${assetId}.${dataFormat}`
    const filePath = `${rootAssetUrl}/${spriteFile}`;
    const wstream = fs.createWriteStream(filePath);
    wstream.on('open', () => {
        let arr = []
        for(let key in data) {
            arr.push(data[key])
        }
        const earray = new Uint8Array(arr)
        wstream.write(earray);
        wstream.end(() => {})
    })
    wstream.on('error', (err) => { console.log('stream error', err) });
    wstream.on('finish', () => {
        const tempCoustume = JSON.parse(JSON.stringify(costumes[0]))
        delete tempCoustume.asset
        const updateCostume = {
            ...tempCoustume,
            name: lowerCaseName,
            md5ext:spriteFile,
            bitmapResolution:2,
            dataFormat,
            rotationCenterX:32,
            rotationCenterY:32
        }
        const newSprite = {
            name: capitalizedName,
            tags:['custom'],
            isStage: false,
            variables: {},
            costumes: [updateCostume],
            sounds:[],
            blocks:{}
        }
        fs.readFile(`${rootJSONUrl}/sprites.json`, 'utf8', function(err, result){
            if (err) {
                return res.send(feedbackMsgErr);
             }
            const parseJSON = JSON.parse(result)
            const strJSON = JSON.stringify([...parseJSON, newSprite])
            const buffer = new Buffer(strJSON)
            fs.writeFile(`${rootJSONUrl}/sprites.json`, buffer, (err) => {
                if (err) return res.send(feedbackMsgErr);
                res.send(feedbackMsg);
            })
        });
    });
})

// bellow item for test purpose;
app.get('/mark/abc',function(req,res){
    const abc = Buffer.from(123)
    //导出数据
    let result={
        data:{
            "data1":"数据一",
            "data2":"数据二",
            "data3":"数据三"
        }
    }
    res.send(result)
})

app.post('/mark/save',function(req,res){
    // req.setEncoding('binary')
    const { body } = req;
    const { costumes } = body;
    const sprite = costumes[0]
    const { assetId, dataFormat, name, asset } = sprite;
    const { data } = asset
    const fileData = data;
    const spriteFile = `${assetId}.${dataFormat}`
    const filePath = `./static/internalapi/asset/${spriteFile}`
    const wstream = fs.createWriteStream(filePath);
    wstream.on('open', () => {
        let arr = []
        for(let key in data) {
            arr.push(data[key])
        }
        const earray = new Uint8Array(arr)
        wstream.write(earray);
    })
    wstream.on('error', (err) => { console.log('stream error') });
    wstream.on('finish', () => { console.log('stream save done') });
    res.send(`Hello World: ${JSON.stringify(req.body)}`)
    // res.send({abc:123})
})

//写方法
app.get('/mark/read',function(req,res){
    fs.readFile('./package.json', 'utf8', function(err, result){
        if (err) {
            return console.log('文件读取失败!' + err.message);
         }
        const parseJSON = JSON.parse(result)
        const strJSON = JSON.stringify({...parseJSON, SNIPER:'HENRY'})
        console.log('文件读取成功，内容是:' + result);
        const buffer = new Buffer(strJSON)
        console.log(buffer, 'buffer')
        fs.writeFile('./package.json', buffer, (err) => {
            if (err) return console.log('write fail')
            console.log('write success')
        })
        res.send({...parseJSON, sniper:'henry'})
    });
})
app.get('/mark/delete',function(req,res){
    console.log(456,'delete')
//导出数据
    let result={
        data:{
            "data1":"数据一",
            "data2":"数据二",
            "data3":"数据三"
        }
    }
    res.send(result)
})


   
//开端口
var server = app.listen(3001,function(){
    console.log('服务器在3001端口打开了');
})